package cn.kxx.serviceImpl;

import cn.kxx.constant.RedisConstant;
import cn.kxx.entity.PageResult;
import cn.kxx.entity.QueryPageBean;
import cn.kxx.exception.BusinessException;
import cn.kxx.mapper.CheckGroupAndItemMapper;
import cn.kxx.mapper.CheckGroupMapper;
import cn.kxx.mapper.CheckItemMapper;
import cn.kxx.mapper.SetmealCheckgroupMapper;
import cn.kxx.pojo.CheckGroup;
import cn.kxx.pojo.CheckGroupAndItem;
import cn.kxx.pojo.SetmealCheckgroup;
import cn.kxx.service.CheckGroupService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    RedisTemplate redisTemplate = new RedisTemplate();
    Logger logger = LoggerFactory.getLogger(CheckItemServiceImpl.class);
    @Autowired
    private SetmealCheckgroupMapper setmealCheckgroupMapper;
    @Autowired
    private CheckGroupAndItemMapper checkGroupAndItemMapper;
    @Autowired
    private CheckItemMapper checkItemMapper;
    @Autowired
    private CheckGroupMapper checkGroupMapper;

    @Transactional
    @Override
    public void add(Integer[] checkitemIds, CheckGroup checkGroup) throws BusinessException {

        String key = RedisConstant.QUERY_CHECKGROUPS_KEY;
        if (redisTemplate.hasKey(key)) {
            redisTemplate.delete(key);
        }
//        检查项不可为空
        if (StringUtils.isEmpty(checkGroup.getName()) || StringUtils.isEmpty(checkGroup.getCode())) {
            throw new BusinessException("检查组为空！不合法");
        }
//判断检查组名字和code是否重复
        if (!checkName(checkGroup.getName()) && !checkCode(checkGroup.getCode())) {
            checkGroupMapper.insert(checkGroup);
        } else {
            throw new BusinessException("检查组重复!!!");
        }

//        添加检查项
        if (checkitemIds != null || checkitemIds.length > 0) {
            Integer id = checkGroup.getId();
            for (Integer checkitemId : checkitemIds) {

                CheckGroupAndItem checkGroupAndItem = new CheckGroupAndItem();
                checkGroupAndItem.setCheckgroupId(id);
                checkGroupAndItem.setCheckitemId(checkitemId);
                checkGroupAndItemMapper.insert(checkGroupAndItem);
            }
        }


    }


    //    检查名字

    private boolean checkName(String name) {

        LambdaQueryWrapper<CheckGroup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CheckGroup::getName, name);
        Integer count = checkGroupMapper.selectCount(lambdaQueryWrapper);
        return count > 0;

    }//    检查code

    private boolean checkCode(String code) {

        LambdaQueryWrapper<CheckGroup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CheckGroup::getCode, code);
        Integer count = checkGroupMapper.selectCount(lambdaQueryWrapper);
        return count > 0;

    }

    //    分页
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Page<CheckGroup> page = new Page<>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        LambdaQueryWrapper<CheckGroup> queryWrapper = null;
        if (!StringUtils.isEmpty(queryPageBean.getQueryString())) {
            queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CheckGroup::getCode, queryPageBean.getQueryString())
                    .or().like(CheckGroup::getName, queryPageBean.getQueryString());
        }
        IPage<CheckGroup> iPage = checkGroupMapper.selectPage(page, queryWrapper);
        return new PageResult(iPage.getTotal(), iPage.getRecords());
    }

//    查询单个检查组
    @Override
    public CheckGroup findById(Integer id) {
        String key = RedisConstant.QUERY_CHECKGROUPS_KEY;
        if (redisTemplate.hasKey(key)){

          List<CheckGroup> list = (List<CheckGroup>) redisTemplate.opsForValue().get(key);
            for (CheckGroup checkGroup : list) {

                if (checkGroup.getId() == id){
                    return checkGroup;
                }
            }
        }else {
            CheckGroup checkGroup = checkGroupMapper.selectById(id);
            return checkGroup;
        }

        return null;
    }

//    查询被选中的检查项
    @Override
    public List<Integer> findCheckItemIdsByCheckGroupId(Integer id) {
        LambdaQueryWrapper<CheckGroupAndItem> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(CheckGroupAndItem::getCheckgroupId,id);
        List<CheckGroupAndItem> list = checkGroupAndItemMapper.selectList(lambdaQueryWrapper);
       List<Integer> list1 = new ArrayList<>();
        for (CheckGroupAndItem checkGroupAndItem : list) {
            list1.add(checkGroupAndItem.getCheckitemId());
        }
        return list1;
    }

//    编辑检查组
    @Transactional
    @Override
    public void edit(Integer[] checkitemIds, CheckGroup checkGroup) {
//删除缓存
        String key = RedisConstant.QUERY_CHECKGROUPS_KEY;
        if (redisTemplate.hasKey(key)){
            redisTemplate.delete(key);
        }

//        判断是否为空
        if (checkGroup == null){
            throw new BusinessException("检查组为空!!");
        }

//        判断是否重复
//        原有group
        String oname = checkGroup.getName();
        String ocode = checkGroup.getCode();
        CheckGroup group = this.findById(checkGroup.getId());

        if ((!ocode.equals(group.getCode())&&checkCode(ocode))||(!oname.equals(group.getName())&&checkName(oname))){
            throw new BusinessException("检查组重复");
        } else{
//        删除原有检查组中间表
            LambdaQueryWrapper<CheckGroupAndItem> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(CheckGroupAndItem::getCheckgroupId,group.getId());
            checkGroupAndItemMapper.delete(lambdaQueryWrapper);
//            添加新的中间表

            for (Integer checkitemId : checkitemIds) {
                CheckGroupAndItem checkGroupAndItem = new CheckGroupAndItem();
                checkGroupAndItem.setCheckitemId(checkitemId);
                checkGroupAndItem.setCheckgroupId(checkGroup.getId());

                checkGroupAndItemMapper.insert(checkGroupAndItem);

            }
//        修改检查组
            checkGroupMapper.updateById(checkGroup);

        }

    }



//    删除检查组
    @Override
    @Transactional
    public void delete(Integer id) {
        String key = RedisConstant.QUERY_CHECKGROUPS_KEY;
        if (redisTemplate.hasKey(key)){
            redisTemplate.delete(key);
        }

//        判断检查组是否有关联
        LambdaQueryWrapper<SetmealCheckgroup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SetmealCheckgroup::getCheckgroupId,id);
        Integer count = setmealCheckgroupMapper.selectCount(lambdaQueryWrapper);
        if (count>0){
            throw new BusinessException("检查组有关联不能删除");
        }
//        删除中间表
        checkGroupAndItemMapper.delete(new LambdaQueryWrapper<CheckGroupAndItem>().eq(CheckGroupAndItem::getCheckgroupId,id));
//        删除检查组
        checkGroupMapper.deleteById(id);

    }

//    动态查询所有检查组
    @Override
    public List<CheckGroup> findAll() throws BusinessException {
        String key = RedisConstant.QUERY_CHECKGROUPS_KEY;
        List<CheckGroup> checkGroups = null;
        if (redisTemplate.hasKey(key)){
            logger.info("=============查询所有检查组findAll()走了缓存！");
            checkGroups = (List<CheckGroup>) redisTemplate.opsForValue().get(key);
        }else {
            logger.info("=============查询所有检查组findAll()走了数据库！");
            checkGroups = checkGroupMapper.selectList(null);
            redisTemplate.opsForValue().set(key,checkGroups);
        }
        return checkGroups;
    }
}
